package mroute

import (
	"github.com/gin-gonic/gin"
	"mygo/mymongo"
	"mygo/mystruct"
	"mygo/global"
	"path/filepath"
	"strings"
	"os"
	"fmt"
)

/* =================================================================================
   在线代码编辑接口
*/
func MycodeModel(cont *gin.Context) {
	code := cont.Query("code")
   codb := mymongo.Get_Code(code)
   if codb == nil {
   	cont.JSON(mystruct.StatusOK, gin.H{"code": mystruct.MyCodeErr, "msg": "标识不存在"})
   	return	
   }
   switch cont.Request.Method {
		case "POST":
			queryid := cont.PostForm("_id")
			name := cont.PostForm("name")
			path := cont.PostForm("path")
			value := cont.PostForm("value")
			if strings.Contains(name+path, "../") {
				cont.JSON(mystruct.StatusOK, gin.H{"code": mystruct.MyCodeErr, "msg": "非法文件名"})
				return
			}
			filePath := filepath.Join(global.Mtoken.Download_Path, codb.Body.Apiid, queryid, name, path)
			if err := os.MkdirAll(filepath.Dir(filePath), 0777); err != nil {
				cont.JSON(mystruct.StatusOK, gin.H{"code": mystruct.MyCodeErr, "msg": err.Error()})
				return
			}
			if err := os.WriteFile(filePath, []byte(value), 0777); err != nil {
				cont.JSON(mystruct.StatusOK, gin.H{"code": mystruct.MyCodeErr, "msg": fmt.Sprintf("保存失败: %v", err)})
				return
			}
			cont.JSON(mystruct.StatusOK, gin.H{"code": mystruct.MyCodeOk, "msg": "保存完成"})

		case "GET":
			queryid := cont.Query("_id")
			name := cont.Query("name")
			path := cont.Query("path")
			filePath := filepath.Join(global.Mtoken.Download_Path, codb.Body.Apiid, queryid, name, path)
			if !mystruct.Exists(filePath) {
				cont.JSON(mystruct.StatusOK, gin.H{"code": mystruct.MyCodeErr, "msg": "文件不存在"})
				return
			}
			fileData, err := os.ReadFile(filePath)
			if err != nil {
				cont.JSON(mystruct.StatusOK, gin.H{"code": mystruct.MyCodeErr, "msg": err.Error()})
				return
			}
			cont.JSON(mystruct.StatusOK, gin.H{"code": mystruct.MyCodeOk, "msg":  string(fileData)})

		default:
			cont.JSON(mystruct.StatusOK, gin.H{"code": mystruct.MyCodeErr, "msg": "不支持的请求方法"})
	}
}